import 'package:flutter/material.dart';
import 'package:flutter_demo/http/http_request.dart';
import 'package:dio/dio.dart';

class FutureDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return FutureDemoState();
  }
}

class FutureDemoState extends State<FutureDemo> {
  String _showStr = 'Unkown';

  @override
  void initState() {
    super.initState();
//    testFuture_01();
//    testFuture_02();
//    testFuture_03();
//    testFuture_04();
//    testFuture_05();
//    testFuture_06();
//    testFuture_07();
    testHttpRequest();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: SingleChildScrollView(
        child: Center(
          child: Text(_showStr),
        ),
      ),
    );
  }

  ///模拟网络访问获取数据，最后展示
  void testFuture_01() {
    Future.delayed(new Duration(seconds: 2), () {
      setState(() => _showStr = 'hi world');
    });
  }

  ///Future异步任务发生错误，可以在catchError中捕获
  void testFuture_02() {
    Future.delayed(Duration(seconds: 3), () {
      throw AssertionError('Error');
    }).then((data) {
      //执行成功代码走这里
      setState(() => _showStr = data);
    }).catchError((e) {
      //执行失败走这里
      setState(() => _showStr = 'error happened');
    });
  }

  ///then方法的可选参数来捕获异常
  void testFuture_03() {
    Future.delayed(Duration(seconds: 3), () {
      throw AssertionError('Error');
    }).then((data) {
      //执行成功代码走这里
      setState(() => _showStr = data);
    }, onError: (e) {
      //执行失败走这里
      setState(() => _showStr = 'error happened ' + e.toString());
    });
  }

  ///测试whenComplete方法
  void testFuture_04() {
    Future.delayed(Duration(seconds: 4), () {
      throw AssertionError('Error');
    }).then((data) {
      //执行成功代码走这里
      setState(() => _showStr = data);
    }, onError: (e) {
      //执行失败走这里
      setState(() => _showStr = e.toString());
    }).whenComplete(() {
      //无论成功或者失败都到这里来
      setState(() => _showStr = 'when complete excute');
    });
  }

  ///多个任务执行完后，一起返回
  void testFuture_05() {
    Future.wait([
      Future.delayed(Duration(seconds: 6), () {
        return 'hello';
      }),
      Future.delayed(Duration(seconds: 5), () {
        return '  -- world';
      })
    ]).then((onValues) {
      setState(() => _showStr = onValues[0] + onValues[1]);
    });
  }

  ///模拟多个任务按顺序执行,这里用Future来消除在then里面一直回调的callback 并输出结果
  void testFuture_06() {
    login('flutter-dart', 'is').then((v1) {
      return getUserInfo(v1);
    }).then((v2) {
      return saveUserInfo(v2);
    }).then((v3) {
      setState(() => _showStr = v3);
    });
  }

  ///利用async和await来实现testFuture_06的过程
  void testFuture_07() async {
    try {
      String loginResult = await login('flutter-dart  ', 'is');
      String userinfoResult = await getUserInfo(loginResult);
      String saveResult = await saveUserInfo(userinfoResult);
      setState(() => _showStr = saveResult);
    } catch (e) {}
  }

  //先分别定义各个异步任务
  Future<String> login(String userName, String pwd) {
    return Future<String>.delayed(Duration(seconds: 2), () {
      return '$userName $pwd';
    });
  }

  Future<String> getUserInfo(String id) {
    return Future<String>.delayed(Duration(seconds: 2), () {
      return '$id very hard,';
    });
  }

  Future<String> saveUserInfo(String userInfo) {
    return Future<String>.delayed(Duration(seconds: 2), () {
      return '$userInfo but developer have to lean it';
    });
  }

  ///利用dio进行一次网络请求
  void testHttpRequest() async {
    Response response = await dio.get("http://www.baidu.com");
    print(response);
    setState(() => _showStr = response.toString());
  }
}
